package com.benjaminwan.read.free.utils

import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.fragment.app.Fragment
import cn.qqtheme.framework.picker.FilePicker
import com.benjaminwan.read.free.R
import com.benjaminwan.read.free.common.OPEN_FILE_REQUEST_CODE
import com.benjaminwan.read.free.common.defaultPath
import com.benjaminwan.read.free.model.action.Script
import com.benjaminwan.read.free.ui.main.MainViewModel
import com.orhanobut.logger.Logger

fun Fragment.loadFromFile(mainVM: MainViewModel) {
    val filePicker = FilePicker(requireActivity(), FilePicker.FILE)
    filePicker.setRootPath(defaultPath)
    filePicker.setShowHideDir(false)
    filePicker.setOnFilePickListener {
        val json = FileIOUtils.readFile2String(it)
        if (json.isNullOrEmpty()) {
            showXToastError(R.string.msg_load_failed)
            return@setOnFilePickListener
        }
        Logger.json(json)
        loadJson(json, mainVM)
    }
    filePicker.show()
}

fun Fragment.loadFromSAF() {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "text/*"
        putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
    }
    startActivityForResult(intent, OPEN_FILE_REQUEST_CODE)
}

fun Fragment.onSAFResult(requestCode: Int, resultCode: Int, data: Intent?, mainVM: MainViewModel) {
    if (data == null || resultCode != Activity.RESULT_OK) return
    if (requestCode == OPEN_FILE_REQUEST_CODE) {
        val uri = data.data ?: return
        loadFromUri(uri, mainVM)
    }
}

fun Fragment.loadFromUri(
    uri: Uri,
    mainVM: MainViewModel
) {
    val json = requireContext().readUri2String(uri)
    if (json.isNullOrEmpty()) {
        showXToastError(R.string.msg_load_failed)
        return
    }
    Logger.json(json)
    loadJson(json, mainVM)
}

fun Fragment.loadJson(
    json: String,
    mainVM: MainViewModel
) {
    val script = fromJsonToActionByMoshi<Script>(json)
    if (script == null) {
        showXToastError(R.string.msg_load_failed)
        return
    } else {
        mainVM.setScript(script)
        showXToastSuccess(R.string.msg_load_success)
    }
}